package com.yeskery.nut.cloud.feign;

import com.yeskery.nut.annotation.bean.Bean;
import com.yeskery.nut.annotation.bean.Configuration;
import com.yeskery.nut.annotation.condition.ConditionalOnBean;
import com.yeskery.nut.annotation.condition.ConditionalOnMissingBean;
import com.yeskery.nut.annotation.condition.ConditionalOnProperty;
import com.yeskery.nut.annotation.condition.ConditionalOnWebApplicationType;
import com.yeskery.nut.bean.ApplicationContext;
import com.yeskery.nut.cloud.loadbanlancer.Breaker;
import com.yeskery.nut.cloud.loadbanlancer.Chooser;
import com.yeskery.nut.cloud.loadbanlancer.CountBreaker;
import com.yeskery.nut.cloud.loadbanlancer.RandomChooser;
import com.yeskery.nut.core.Environment;

/**
 * feign客户端注册器
 * @author YESKERY
 * 2024/1/9
 */
@Configuration
public class FeignClientsRegistrar {

    /**
     * feign客户端import注解注册器
     * @return feign客户端import注解注册器
     */
    @Bean
    public FeignClientsImportBeanRegistrar feignClientsImportBeanRegistrar() {
        return new FeignClientsImportBeanRegistrar();
    }

    /**
     * 默认的feign请求处理类
     * @param applicationContext 应用上下文
     * @return 默认的feign请求处理类
     */
    @Bean
    @ConditionalOnMissingBean(FeignRequestHandler.class)
    public DefaultFeignRequestHandler defaultFeignRequestHandler(ApplicationContext applicationContext) {
        return new DefaultFeignRequestHandler(applicationContext);
    }

    /**
     * 默认的Feign 响应转换<code>application/json</code>实现类bean
     * @param applicationContext 应用上下文
     * @return 默认的Feign 响应转换<code>application/json</code>实现类bean
     */
    @Bean
    @ConditionalOnMissingBean(FeignResponseConvert.class)
    public FeignResponseConvert defaultApplicationJsonFeignResponseConvert(ApplicationContext applicationContext) {
        return new ApplicationJsonFeignResponseConvert(applicationContext);
    }

    /**
     * 默认的Http配置支持接口
     * @param environment 环境对象
     * @return 默认的Http配置支持接口
     */
    @Bean
    @ConditionalOnMissingBean(HttpConfigurationSupport.class)
    @ConditionalOnBean(DefaultFeignRequestHandler.class)
    public HttpConfigurationSupport defaultHttpConfigurationSupport(Environment environment) {
        return new DefaultHttpConfigurationSupport(environment);
    }

    /**
     * 默认的负载均衡选择器
     * @return 默认的负载均衡选择器
     */
    @Bean
    @ConditionalOnWebApplicationType
    @ConditionalOnMissingBean(Chooser.class)
    public Chooser defaultFeignClientChooser() {
        return new RandomChooser();
    }

    /**
     * 默认的计数熔断器
     * @return 默认的计数熔断器
     */
    @Bean
    @ConditionalOnWebApplicationType
    @ConditionalOnProperty(value = "nut.cloud.breaker.counter.enable", havingValue = "true")
    public Breaker defaultCountBreaker() {
        return new CountBreaker();
    }
}
